package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type RetailsData struct {
	Id            int64
	Retails       *Retails        `orm:"rel(fk);null;on_delete(do_nothing)"`
	Products      *ErpProducts    `orm:"rel(fk);null;on_delete(do_nothing)"`
	Inventory     *ErpInventory   `orm:"rel(fk);null;on_delete(do_nothing)"`
	Snd           *ErpProductsSnd `orm:"rel(fk);null;on_delete(do_nothing)"`
	Custom        *RetailsCustom  `orm:"rel(fk);null;on_delete(do_nothing)"`
	ReserveNum    int64   //库存量
	Amount        int64   //产品数量
	CollectNum    int64   //提货数量
	CollectDate   int64   //提货时间
	ReturnNum     int64   //退货数量
	OriginalPrice float64 //产品原价
	DiscountRate  float64 //产品折扣率
	UnitPrice     float64 //产品折后单价
	TotalPrice    float64 //折后单价*产品数量
}

func RetailsDataTableName() string {
	return TableName("sa_retails_data")
}

func (a *RetailsData) TableName() string {
	return RetailsDataTableName()
}

type RetailsDataQueryParam struct {
	BaseQueryParam
	RetailsId   int64
	Archives    int64  `json:"archives_id"`
	ProductName string `json:"product_name"`
	Deps        []string
	RelatedSel  []interface{}
}

//查询列表数据
func RetailsDataList(params *RetailsDataQueryParam) ([]*RetailsData, int64) {

	query := orm.NewOrm().QueryTable(RetailsDataTableName())
	if len(params.RelatedSel) > 0 {
		query = query.RelatedSel(params.RelatedSel...)
	}
	data := make([]*RetailsData, 0)

	if params.RetailsId > 0 {
		query = query.Filter("retails_id", params.RetailsId)
	}
	if params.Archives > 0 {
		query = query.Filter("Retails__Archives__Id", params.Archives)
	}
	if len(params.Deps) > 0 {
		query = query.Filter("Retails__DepartmentId__in", params.Deps)
	}
	if len(params.ProductName) > 0 {
		query = query.Filter("Products__Name__icontains", params.ProductName)
	}

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}
